<template>
  <div class="personal-center-container">
    <el-row class="posirow" :gutter="20">
      <el-col :lg="8">
        <el-card shadow="hover" :style="{ height: cardHeight() + 'px' }">
          <div class="personal-center-user-info">
            <el-avatar :size="100" :src="avatarImg" />
            <div class="personal-center-user-info-full-name">
              {{ userDetail.nickName }}
            </div>
            <div class="personal-center-user-info-description">
              {{ userDetail.memo }}
            </div>
            <!-- <div class="personal-center-user-info-follow">
              <a>
                <el-button round type="primary">
                  <vab-icon icon="group-line" />
                  Follow me
                </el-button>
              </a>
            </div> -->

            <ul class="personal-center-user-info-list">
              <li>
                <vab-icon icon="community-line" />
                {{ nodename }}
              </li>
              <!-- <li>
                <vab-icon icon="magic-line" />
                1992/03/02
              </li> -->
              <li>
                <vab-icon icon="women-line" />
                {{ sexnames }}
              </li>
              <li>
                <vab-icon icon="smartphone-line" />
                {{ userDetail.phonenumber }}
              </li>
              <li>
                <vab-icon icon="mail-open-line" />
                {{ userDetail.email }}
              </li>
              <!-- <li>
                <vab-icon icon="code-s-slash-line" />
                JavaScript、HTML、CSS、Vue、Node
              </li> -->
              <!-- <li>
                <el-divider />
                <h5>个性标签</h5>
                <el-tag size="small">腹黑</el-tag>
                <el-tag size="small">怕麻烦</el-tag>
                <el-tag size="small">小仙女</el-tag>
                <el-tag size="small">仙气飘飘</el-tag>
              </li> -->
            </ul>
          </div>
        </el-card>
      </el-col>
      <el-col :lg="16">
        <el-card shadow="hover" :style="{ height: cardHeight() + 'px' }">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="基本信息修改" name="first">
              <el-col :lg="12">
                <el-form ref="form" v-loading="formLoading" class="overscroll" label-width="80px" :model="userDetail">
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="管理机构">
                        <el-input v-model="nodename" disabled="disabled" readonly />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="登录名称">
                        <el-input v-model="userDetail.userName" disabled="disabled" readonly />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="用户头像">
                        <UploadImage
                          :image-url="userDetail.avatar"
                          type="avatar"
                          :upload-params="{
                            moduleName: 'systemUser',
                            entityId: userDetail.id
                          }"
                          @on-success="onHandleSuccess"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12" />
                  </el-row>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="用户昵称">
                        <el-input v-model="userDetail.nickName" placeholder="请填写昵称" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="性别" prop="sex">
                        <el-select v-model="userDetail.sex" clearable placeholder="性别" style="width: 100%">
                          <el-option
                            v-for="item in sexEnum"
                            :key="item.dictValue"
                            :label="item.dictLabel"
                            :value="item.dictValue"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="手机">
                        <el-input v-model="userDetail.phonenumber" placeholder="请填写手机号" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="邮箱">
                        <el-input v-model="userDetail.email" placeholder="请填写邮箱" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="24">
                      <el-form-item label="用户描述">
                        <el-input v-model="userDetail.memo" placeholder="请填写用户描述" :rows="2" type="textarea" />
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-form-item style="text-align: center">
                    <el-button :icon="Check" type="primary" @click="saveProfile"> 保存 </el-button>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-tab-pane>
            <el-tab-pane label="密码修改" name="second">
              <el-col :lg="12">
                <el-form
                  ref="formpasw"
                  v-loading="pwdformLoading"
                  label-position="left"
                  label-width="80px"
                  :model="changePwd"
                  :rules="rules"
                >
                  <el-form-item label="旧密码" prop="oldpassword">
                    <el-input v-model="changePwd.oldpassword" placeholder="请输入旧密码" show-password />
                  </el-form-item>
                  <el-form-item label="新密码" prop="newpassword">
                    <el-input v-model="changePwd.newpassword" placeholder="请输入新密码" show-password />
                  </el-form-item>
                  <el-form-item label="确认密码" prop="confirmpassword">
                    <el-input v-model="changePwd.confirmpassword" placeholder="再次填写确认" show-password />
                  </el-form-item>
                  <el-form-item>
                    <el-button :icon="Check" type="primary" @click="savepassword"> 确认 </el-button>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { Check } from "@element-plus/icons-vue";
import { useUserStore } from "@/stores/modules/user";
// import { translate } from "@/i18n";
import { isPassword } from "@/utils/eleValidate";
// import VabCropper from "@/plugins/VabCropper/index.vue";
import { getRequest, getLocalStorage, postRequest } from "@/api/mains";
import UploadImage from "@/plugins/upload/UploadImage.vue";
import { staticURL } from "@/config";
import md5 from "js-md5";
import { storeToRefs } from "pinia";
import { backTableHeight } from "@/api/mains";
import { failMsg, succMsg } from "@/utils/MessageUtils";

export default {
  name: "PersonalList",
  components: { /* VabCropper,  */ UploadImage },
  setup() {
    const userStore = useUserStore();
    const { avatar, userid } = storeToRefs(userStore);

    const cardHeight = () => {
      return backTableHeight() + 160;
    };

    const validatePassword = (rule, value, callback) => {
      //if (!isPassword(value)) callback(new Error(translate("密码不能少于6位")));
      if (!isPassword(value)) callback(new Error("密码不能少于6位"));
      else callback();
    };
    const avatarImg = ref("");
    const state = reactive({
      vabCropperRef: null,
      formpasw: null,
      form: null,
      formLoading: false,
      pwdformLoading: false,
      activeName: "first",
      url: "system/user",
      userid: userid,
      userDetail: {},
      sexEnum: [],
      nodename: "",
      sexnames: "",
      changePwd: {
        newpassword: "",
        oldpassword: "",
        confirmpassword: ""
      },
      rules: {
        newpassword: [
          {
            required: true,
            trigger: "blur",
            validator: validatePassword
          }
        ],
        oldpassword: [
          {
            required: true,
            trigger: "blur",
            validator: validatePassword
          }
        ],
        confirmpassword: [
          {
            required: true,
            trigger: "blur",
            validator: validatePassword
          }
        ]
      }
    });

    const handleClick = () => {
      // if (state.activeName == 'second') {
      //   getUserDetailList()
      // }
    };
    const getUserDetailList = async () => {
      state.formLoading = true;
      const res = await getRequest("system/user/getUserInfo");
      state.formLoading = false;
      state.userDetail = res.data;
      //枚举数据缓存
      state.sexEnum = getLocalStorage().sys_user_sex;
      state.nodename = state.userDetail.orgName;
      if (state.userDetail.avatar) {
        avatarImg.value = `${staticURL}/${state.userDetail.avatar}`;
      } else {
        avatarImg.value = `/avatar.gif`;
      }
      if (state.userDetail.sex) {
        //用户管理那边性别不是必填，为空时报错
        const sexItem = state.sexEnum.find(citem => citem.dictValue == state.userDetail.sex)?.dictLabel;
        state.sexnames = sexItem || state.userDetail.sex;
      }
    };

    const onHandleSuccess = async datas => {
      const { originalImgUri } = datas;
      state.userDetail.avatar = originalImgUri;
    };

    const openDialog = () => {
      state["vabCropperRef"].dialogVisible = true;
    };

    const savepassword = () => {
      if (state.changePwd.newpassword == state.changePwd.confirmpassword) {
        state["formpasw"].validate(async valid => {
          if (valid) {
            state.pwdformLoading = true;
            const { code, msg } = await postRequest(state.url + "/changePwd", {
              oldpassword: md5(state.changePwd.oldpassword),
              newpassword: md5(state.changePwd.newpassword)
            });
            state.pwdformLoading = false;
            if (code == 200) {
              succMsg(msg);
            }
          }
        });
      } else {
        failMsg("确认密码与新密码不符，请重新输入！");
        state.changePwd.confirmpassword = "";
      }
    };

    const saveProfile = () => {
      state["form"].validate(async valid => {
        if (valid) {
          state.formLoading = true;
          const { code, msg } = await postRequest("system/user/updateProfile", state.userDetail);
          state.formLoading = false;
          if (code == 200) {
            succMsg(msg);
            getUserDetailList();
          }
        }
      });
    };
    getUserDetailList();
    return {
      ...toRefs(state),
      avatar,
      avatarImg,
      openDialog,
      savepassword,
      saveProfile,
      handleClick,
      onHandleSuccess,
      Check,
      cardHeight
    };
  }
};
</script>

<style lang="scss" scoped>
$base: ".personal-center";
#{$base}-container {
  position: relative;
  padding: 0 !important;
  background: $base-color-background !important;
  :deep() {
    .posirow {
      position: absolute;
      inset: 0;
      .el-col {
        height: 100%;
      }
    }
    .el-card {
      //height: 100%;
      margin-bottom: 0 !important;
      .el-card__body {
        // height: 100%;
        padding: 10px;
        padding-right: 0;
        padding-bottom: 0;
      }
    }
    .el-tabs {
      height: 100%;
      .el-tabs__content,
      .el-tab-pane {
        height: 96%;
      }
    }
    .overscroll {
      height: 88%;
      overflow-y: scroll;
    }
    .el-tab-pane .el-col {
      float: initial;
      max-width: initial;
    }
  }

  #{$base}-user-info {
    padding: $base-padding;
    text-align: center;
    :deep() {
      .el-avatar {
        img {
          cursor: pointer;
        }
      }
    }
    &-full-name {
      margin-top: 15px;
      font-size: 24px;
      font-weight: 500;
      color: #262626;
    }
    &-description {
      margin-top: 8px;
      font-size: 12px;
      color: #666666;
    }
    &-follow {
      margin-top: 15px;
    }
    &-list {
      margin-top: 18px;
      line-height: 30px;
      text-align: left;
      list-style: none;
      h5 {
        margin: -20px 0 5px;
      }
      :deep() {
        .el-tag {
          margin-right: 10px !important;
        }
        .el-tag + .el-tag {
          margin-left: 0;
        }
      }
    }
  }

  #{$base}-item {
    display: flex;
    i {
      font-size: 40px;
    }
    &-content {
      box-sizing: border-box;
      flex: 1;
      margin-left: $base-margin;
      &-second {
        margin-top: 8px;
      }
    }
  }
}
</style>
